import React, { useState, useEffect } from 'react';

const ProcessInput = ({ processCount, deadlockProcesses, onProcessesChange }) => {
    const [selectedProcesses, setSelectedProcesses] = useState(deadlockProcesses);

    useEffect(() => {
        setSelectedProcesses(deadlockProcesses);
    }, [deadlockProcesses]);

    const toggleProcess = (processId) => {
        const newSelected = [...selectedProcesses];
        const index = newSelected.indexOf(processId);

        if (index === -1) {
            newSelected.push(processId);
        } else {
            newSelected.splice(index, 1);
        }

        setSelectedProcesses(newSelected);
        onProcessesChange(newSelected);
    };

    return (
        <div className="process-input">
            <h3>死锁进程选择</h3>
            <div className="process-grid">
                {[...Array(processCount)].map((_, i) => (
                    <div
                        key={`process-${i}`}
                        className={`process-card ${selectedProcesses.includes(i) ? 'selected' : ''}`}
                        onClick={() => toggleProcess(i)}
                    >
                        P{i + 1}
                    </div>
                ))}
            </div>
        </div>
    );
};

export default ProcessInput;